package iet.jxufe.cn.android.productanti_counterfeitingtraceabilitysystem.utils;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class SmsUtils {
    /**
     * @deprecated 模拟短信发送功能的一种可行实现。
     *             使用前在AndroidManifest里添加android:usesCleartextTraffic="true"。
     */
    @Deprecated
    public static class SmsTask extends AsyncTask<String, Void, String> {
        private static final String TAG = "NetworkTask";
        private final String device = "emulator-5554";

        @Override
        protected String doInBackground(String... params) {
            String phoneNumber = params[0];  // 获取第一个参数
            String message = params[1];       // 获取第二个参数

            String response = "";

            try {
                // 构建动态 URL，拼接参数
                String baseUrl = "http://10.0.2.2:5000/run_python_script?";
                String query = "device=" + URLEncoder.encode(device, StandardCharsets.UTF_8.name()) +
                        "&phone_number=" + URLEncoder.encode(phoneNumber, StandardCharsets.UTF_8.name()) +
                        "&message=" + URLEncoder.encode(message, StandardCharsets.UTF_8.name());

                String urlString = baseUrl + query;

                // 创建 URL 对象
                URL url = new URL(urlString);

                // 创建 HttpURLConnection 对象
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                // 设置请求方式
                urlConnection.setRequestMethod("GET");
                urlConnection.setConnectTimeout(15000);
                urlConnection.setReadTimeout(15000);

                // 读取服务器响应
                BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                String line;
                StringBuilder stringBuilder = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                response = stringBuilder.toString();
                reader.close();

            } catch (IOException e) {
                Log.e(TAG, "Network error", e);
            }
            return response;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.d(TAG, "Response: " + result);
        }
    }
}
